package handlers

import (
	"github.com/gin-gonic/gin"
	"store-master/models"
	"strconv"
)

func AddShop(c *gin.Context) {
	shop_name := c.PostForm("shop_name")
	address := c.PostForm("address")
	if shop_name == "" || address == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	shop := models.Shop{
		ShopName: shop_name,
		Address:  address,
	}

	err := models.DB.Create(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func ListShop(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var shops []models.Shop

	models.DB.Offset(offset).Limit(size).Find(&shops)

	var total int64
	models.DB.Model(&models.Shop{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  shops,
		"total": total,
	})
	return
}
